package org.vsaulyak.springrssagregator.bean;

import java.io.IOException;
import java.util.List;
import java.util.ArrayList;
import java.net.URL;
import java.net.MalformedURLException;
import org.vsaulyak.springrssagregator.entity.Item;
import org.vsaulyak.springrssagregator.entity.Chanel;
import org.vsaulyak.springrssagregator.exception.ChanelParsingException;
import com.sun.syndication.feed.synd.SyndFeed;
import com.sun.syndication.feed.synd.SyndEntry;
import com.sun.syndication.io.FeedException;
import com.sun.syndication.io.SyndFeedInput;
import com.sun.syndication.io.XmlReader;

public class RssChanelParser extends ChanelParser
{
    
    
    @Override
    public void parseItems(Chanel chanel) throws ChanelParsingException
    {
        List<Item> items = new ArrayList<Item>();
        SyndFeed feed = parseFeed(chanel.getLink());
        for (Object object : feed.getEntries())
        {
            SyndEntry entry = (SyndEntry) object;
            Item item = new Item();
            item.setRank(0);
            item.setLink(entry.getLink().trim());
            item.setTitle(entry.getTitle().trim());
            items.add(item);
        }
        chanel.setItems(items);
    }
    
    private SyndFeed parseFeed(String url) throws ChanelParsingException
    {
        try
        {
            return new SyndFeedInput().build(new XmlReader(new URL(url)));
        }
        catch (IllegalArgumentException e)
        {
            throw new ChanelParsingException(e.getMessage());
        }
        catch (MalformedURLException e)
        {
            throw new ChanelParsingException(e.getMessage());
        }
        catch (FeedException e)
        {
            throw new ChanelParsingException(e.getMessage());
        }
        catch (IOException e)
        {
            throw new ChanelParsingException(e.getMessage());
        }
    }
}
